import React, { useState, useEffect } from 'react';
import { Card, Typography, Table, Button, message, Empty, Popconfirm } from 'antd';
import { DeleteOutlined, ExportOutlined, ReloadOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { getHistory, clearHistory } from '../../components/utils/calculationHistory';
import notificationService from '../../services/notificationService';

// 从localStorage获取历史记录最大数量设置
const getHistoryMaxCount = (): number => {
  try {
    const appSettings = localStorage.getItem('appSettings');
    if (appSettings) {
      const settings = JSON.parse(appSettings);
      if (settings.historyMaxCount && typeof settings.historyMaxCount === 'number') {
        return settings.historyMaxCount;
      }
    }
  } catch (error) {
    console.error('Failed to get historyMaxCount:', error);
  }
  return 20; // 默认值
}

const { Title } = Typography;

// 定义计算历史记录的数据类型
interface CalculationRecord {
  id: string;
  title: string;
  calculationType: string;
  timestamp: number;
  results: any;
  params: Record<string, any>;
}

const CalculationHistoryPage: React.FC = () => {
  const [dataSource, setDataSource] = useState<CalculationRecord[]>([]);
  const [loading, setLoading] = useState(true);

  // 加载计算历史记录
  const loadHistory = async () => {
    setLoading(true);
    try {
      const items = getHistory();
      setDataSource(items as CalculationRecord[]);
    } catch (error) {
  notificationService.error('加载计算历史失败');
      console.error('Failed to load calculation history:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadHistory();
  }, []);
  
  // 监听appSettings变化，当历史记录个数设置改变时重新加载历史记录
  useEffect(() => {
    // 初始加载历史记录最大数量
    let currentMaxCount = getHistoryMaxCount();
    
    // 创建一个自定义事件监听器
    const handleSettingsChange = () => {
      const newMaxCount = getHistoryMaxCount();
      if (newMaxCount !== currentMaxCount) {
        currentMaxCount = newMaxCount;
        loadHistory(); // 重新加载历史记录
      }
    };
    
    // 监听localStorage的变化
    const handleStorageChange = (event: StorageEvent) => {
      if (event.key === 'appSettings') {
        handleSettingsChange();
      }
    };
    
    // 监听自定义事件，当在同一窗口内修改设置时触发
    const handleAppSettingsChange = (event: Event) => {
      const customEvent = event as CustomEvent;
      if (customEvent.detail && customEvent.detail.historyMaxCount !== undefined) {
        handleSettingsChange();
      }
    };
    
    // 监听当前窗口的storage事件和自定义事件
    window.addEventListener('storage', handleStorageChange);
    window.addEventListener('app-settings-changed', handleAppSettingsChange);
    
    return () => {
      window.removeEventListener('storage', handleStorageChange);
      window.removeEventListener('app-settings-changed', handleAppSettingsChange);
    };
  }, []);

  // 刷新历史记录
  const handleRefresh = () => {
    loadHistory();
  };

  // 删除单条记录
  const handleDelete = (id: string) => {
    try {
      const updatedHistory = dataSource.filter(item => item.id !== id);
      setDataSource(updatedHistory);
      // persist
      localStorage.setItem('calculationHistory', JSON.stringify(updatedHistory));
  notificationService.success('删除成功');
    } catch (error) {
  notificationService.error('删除失败');
      console.error('Failed to delete record:', error);
    }
  };

  // 清空所有记录
  const handleClearAll = () => {
    try {
      setDataSource([]);
      clearHistory();
  notificationService.success('已清空所有历史记录');
    } catch (error) {
  notificationService.error('清空失败');
      console.error('Failed to clear history:', error);
    }
  };

  // 导出记录
  const handleExport = () => {
    if (dataSource.length === 0) {
  notificationService.warning('没有可导出的记录');
      return;
    }

    try {
      // 创建导出内容
      const exportContent = JSON.stringify(dataSource, null, 2);
      const blob = new Blob([exportContent], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `calculation-history-${new Date().toISOString().split('T')[0]}.json`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
  notificationService.success('导出成功');
    } catch (error) {
  notificationService.error('导出失败');
      console.error('Failed to export history:', error);
    }
  };

  // 定义表格列
  const columns: ColumnsType<CalculationRecord> = [
    {
      title: '计算类型',
      dataIndex: 'calculationType',
      key: 'calculationType',
    },
    {
      title: '计算名称',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '计算时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      render: (ts: number) => new Date(ts).toLocaleString(),
    },
    {
      title: '计算结果',
      dataIndex: 'results',
      key: 'results',
      ellipsis: true,
      width: 200,
      render: (val) => {
        try {
          if (!val) return '';
          if (typeof val === 'string') return val;
          return JSON.stringify(val);
        } catch (e) {
          return String(val);
        }
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Popconfirm
          title="确定要删除这条记录吗？"
          onConfirm={() => handleDelete(record.id)}
          okText="确定"
          cancelText="取消"
        >
          <Button type="text" danger icon={<DeleteOutlined />}>
            删除
          </Button>
        </Popconfirm>
      ),
    },
  ];

  return (
    <div>
      <Title level={2}>计算历史</Title>
      
      <Card>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <Button 
              type="primary" 
              icon={<ExportOutlined />} 
              onClick={handleExport}
              disabled={dataSource.length === 0}
            >
              导出记录
            </Button>
            <Button 
              style={{ marginLeft: 12 }} 
              icon={<ReloadOutlined />} 
              onClick={handleRefresh}
            >
              刷新
            </Button>
          </div>
          <Popconfirm
            title="确定要清空所有历史记录吗？"
            onConfirm={handleClearAll}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              danger 
              disabled={dataSource.length === 0}
            >
              清空所有记录
            </Button>
          </Popconfirm>
        </div>
        
        {dataSource.length === 0 && !loading ? (
          <Empty 
            description="暂无计算历史记录" 
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        ) : (
          <Table
            columns={columns}
            dataSource={dataSource}
            rowKey="id"
            loading={loading}
            pagination={{ pageSize: 10 }}
          />
        )}
      </Card>
    </div>
  );
};

export default CalculationHistoryPage;